package com.fast.cron.servlet;

import com.fast.cron.db.dao.UserDao;
import com.fast.cron.db.entry.User;
import com.fast.cron.db.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author: Leo Jie
 * @date: 2018-10-07 20:55
 * @version: v1.0
 */
public class LoginServlet extends AbstractFastCronServlet {
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final Logger logger = LoggerFactory.getLogger(LoginServlet.class);
    private final UserDao userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (hasParam(req, USERNAME) && hasParam(req, PASSWORD)) {
            String username = getParam(req, USERNAME);
            String password = getParam(req, PASSWORD);
            logger.info("{} is logging in.", username);
            try {
                User user = userService.findOneUserByUsernameAndPassword(username, password);
                if (null == user) {
                    logger.info("{},logan failed.", username);
                } else {
                    logger.info("{},logan successfully.", username);
                    successResponseResult(resp);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                errorResponseResult(resp, e.getMessage());
            }
        } else {
            errorResponseResult(resp, "param error.");
        }
    }
}